var express = require('express');
var bodyParser = require('body-parser');
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var db = require('../db.js')
var router = express.Router()

// post .body  /  get .query

/**
 * Promise.all 等待所有异步操作都完成（或第一个失败）
 * 
 * Promise.all([p1, p2, p3]).then(values => { 
 *  console.log(values); // 返回的结果是一个数组
 * });
 */

router.get("/list", async function (req, res) {
  var sql = `select * from classify order by id asc`
  // var data = await Promise.all([db.doSQL(sql)])
  let { data } = await db.doSQL(sql)
  res.send(db.handerResult(data))
})

router.post("/sendlist", urlencodedParser, async function (req, res) {
  let { name, type } = req.body
  let sql = `insert into classify (name,type) values ('${name}','${type}')`
  let { data } = await db.doSQL(sql)
  res.send(db.handerResult(data))
})

router.post("/editlist", urlencodedParser, async function (req, res) {
  let { id, name, type } = req.body
  let sql = `update classify set name='${name}',type='${type}' where id=${id} `
  let { data } = await db.doSQL(sql)
  res.send(db.handerResult(data))
})

router.get('/delList', async function (req, res) {
  var ids = req.query.id;
  var sql = `delete from classify where id in (${ids})`;
  const { data } = await db.doSQL(sql)
  res.send(db.handerResult(data))
})


module.exports = router;